package com.ssy.lingxi.member.merchant.serviceimpl.web;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberStatusEnum;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.PasswordUtil;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.api.model.constant.MemberProcessTypeEnum;
import com.ssy.lingxi.member.merchant.config.ServiceConfig;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.bo.*;
import com.ssy.lingxi.member.merchant.model.constant.*;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.*;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.*;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.response.*;
import com.ssy.lingxi.member.merchant.model.vo.platform.response.RoleRuleManageVO;
import com.ssy.lingxi.member.merchant.model.vo.validate.request.*;
import com.ssy.lingxi.member.merchant.model.vo.validate.response.WorkFlowStepVO;
import com.ssy.lingxi.member.merchant.repository.*;
import com.ssy.lingxi.member.merchant.service.base.*;
import com.ssy.lingxi.member.merchant.service.feign.IReportFeignService;
import com.ssy.lingxi.member.merchant.service.feign.IWorkflowFeignService;
import com.ssy.lingxi.member.merchant.service.web.IMemberAbilityImportService;
import com.ssy.lingxi.member.merchant.service.web.IPlatformMemberRoleRuleService;
import com.ssy.lingxi.member.merchant.utils.AgentAreaUtil;
import com.ssy.lingxi.member.merchant.utils.NumberUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 会员能力 - 会员导入相关接口实现
 * @author 万宁
 * @version 2.0.0
 * @date 2020-08-18
 */
@Service
public class MemberAbilityImportServiceImpl implements IMemberAbilityImportService {
    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberTypeRepository memberTypeRepository;

    @Resource
    private ChannelTypeRepository channelTypeRepository;

    @Resource
    private MemberUserRepository memberUserRepository;

    @Resource
    private MemberRelationRepository relationRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private IBaseMemberRegisterDetailService baseMemberRegisterDetailService;

    @Resource
    private IBaseMemberLevelConfigService baseMemberLevelConfigService;

//
//    @Resource
//    private BaseLevelConfigRepository baseLevelConfigRepository;

    @Resource
    private IBasePlatformProcessService basePlatformProcessService;

    @Resource
    private IBaseMemberInnerService memberInnerService;

    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private CountryCodeRepository countryCodeRepository;

    @Resource
    private IBaseMemberHistoryService baseMemberHistoryService;

    @Resource
    private IBaseMemberValidateService baseMemberValidateService;

    @Resource
    private IWorkflowFeignService baseWorkflowService;

    @Resource
    private IReportFeignService reportFeignService;

    @Resource
    private IBaseSiteService siteService;

    @Resource
    private IPlatformMemberRoleRuleService roleRuleService;

    /**
     * 会员导入功能所需要的外部状态列表
     */
    private final List<MemberOuterStatusEnum> memberImportOuterStatus = Stream.of(MemberOuterStatusEnum.TO_PLATFORM_VERIFY, MemberOuterStatusEnum.PLATFORM_VERIFYING, MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED).collect(Collectors.toList());

    /**
     * 获取分页查询会员列表页面中各个查询条件下拉选择框的内容
     *
     * @param headers HttpHeaders信息
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberImportSearchConditionVO> getPageCondition(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //规则：
        // 1). 上级会员角色为企业会员，下级会员角色为企业会员：无限制
        // 2). 上级会员角色为企业会员，下级会员角色为渠道会员：不允许创建
        // 3). 上级会员角色为渠道会员，下级会员角色为企业会员：不允许创建
        // 4). 上级会员角色为渠道会员，下级会员角色为渠道会员：判断下级会员是否有另一个服务消费者角色在关系树中

        MemberImportSearchConditionVO conditionVO = new MemberImportSearchConditionVO();

        //外部状态
        List<DropdownItem> itemList = memberImportOuterStatus.stream().map(e -> new DropdownItem(e.getCode(), e.getMsg())).collect(Collectors.toList());
        itemList.add(0 , new DropdownItem(0, MemberStringEnum.CHOOSE.getName()));
        conditionVO.setOuterStatus(itemList);

        //状态
        itemList = MemberStatusEnum.toList().stream().map(status -> new DropdownItem(status, MemberStatusEnum.getCodeMessage(status))).collect(Collectors.toList());
        itemList.add(0 , new DropdownItem(0, MemberStringEnum.CHOOSE.getName()));
        conditionVO.setStatus(itemList);

        //获取是否开启saas多租户部署
        Boolean enableMultiTenancy = siteService.isEnableMultiTenancy(headers).getData();

        List<MemberTypeIdAndNameVO> memberTypeList;
        List<RoleIdAndNameVO> roleList;
        if (enableMultiTenancy) {//有开启
            //会员类型（这里返回的是Id）
            memberTypeList = baseMemberValidateService.getSubMemberTypeList(loginUser.getMemberType(), Optional.ofNullable(roleRuleService.subMemberRoles(loginUser.getMemberId())).map(Wrapper::getData).orElse(new ArrayList<>()));
            //会员角色（按照Id升序排序）
            roleList = baseMemberValidateService.getSubRoleList(loginUser.getMemberType(), Optional.ofNullable(roleRuleService.subMemberRoles(loginUser.getMemberId())).map(Wrapper::getData).orElse(new ArrayList<>()));
        } else {//未开启
            //会员类型（这里返回的是Id）
            memberTypeList = baseMemberValidateService.getSubMemberTypeList(loginUser.getMemberType());
            //会员角色（按照Id升序排序）
            roleList = baseMemberValidateService.getSubRoleList(loginUser.getMemberType());
        }
        memberTypeList.add(0, new MemberTypeIdAndNameVO(0L, MemberStringEnum.CHOOSE.getName()));
        conditionVO.setMemberTypes(memberTypeList);
        roleList.add(0, new RoleIdAndNameVO(0L, MemberStringEnum.CHOOSE.getName()));
        conditionVO.setMemberRoles(roleList);

        //会员等级
        List<LevelAndTagVO> levelList = baseMemberLevelConfigService.listSubMemberLevels(loginUser.getMemberId(), loginUser.getMemberRoleId());
        conditionVO.setMemberLevels(levelList);

        return Wrapper.success(conditionVO);
    }

    /**
     * 分页、模糊查询会员
     *
     * @param headers HttpHeaders信息
     * @param queryVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberAbilityImportPageQueryVO>> pageMembers(HttpHeaders headers, MemberAbilityImportMemberQueryVO queryVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> spec = (Specification<MemberRelationDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //上级会员id和角色Id
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));

            //注册来源要为“商户代录入注册”或“渠道代录入注册”
            list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("relSource").as(Integer.class), MemberRelationSourceEnum.MEMBER_CREATE.getCode()), criteriaBuilder.equal(root.get("relSource").as(Integer.class), MemberRegisterSourceEnum.FROM_CHANNEL_IMPORT.getCode())));

            //会员名称
            if(StringUtils.hasLength(queryVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + queryVO.getName().trim() + "%"));
            }

            //注册起始日期
            if(StringUtils.hasLength(queryVO.getStartDate())) {
                LocalDateTime startDate = LocalDateTime.parse(queryVO.getStartDate().concat(" 00:00:00"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), startDate));
            }

            //注册结束日期
            if(StringUtils.hasLength(queryVO.getEndDate())) {
                LocalDateTime endDate = LocalDateTime.parse(queryVO.getEndDate().concat(" 23:59:59"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(LocalDateTime.class), endDate));
            }

            //外部状态
            if(NumberUtil.isNullOrZero(queryVO.getOuterStatus())) {
                list.add(root.get("outerStatus").as(Integer.class).in(memberImportOuterStatus.stream().map(MemberOuterStatusEnum::getCode).collect(Collectors.toList())));
            } else {
                list.add(criteriaBuilder.equal(root.get("outerStatus").as(Integer.class), queryVO.getOuterStatus()));
            }

            //状态
            if(NumberUtil.notNullOrZero(queryVO.getStatus())) {
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), queryVO.getStatus()));
            }

            //会员角色
            if(NumberUtil.notNullOrZero(queryVO.getRoleId())) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), queryVO.getRoleId()));
            }

            //会员等级
            if(NumberUtil.notNullOrZero(queryVO.getLevel())) {
                Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), queryVO.getLevel()));
            }

            //会员类型
            if(NumberUtil.notNullOrZero(queryVO.getMemberTypeId())) {
                Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
                list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("id").as(Long.class), queryVO.getMemberTypeId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(queryVO.getCurrent() - 1, queryVO.getPageSize(), Sort.by("id").descending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(spec, page);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberAbilityImportPageQueryVO memberVO = new MemberAbilityImportPageQueryVO();
            memberVO.setMemberId(relationDO.getSubMember().getId());
            memberVO.setValidateId(relationDO.getId());
            memberVO.setName(relationDO.getSubMember().getName());
            memberVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            memberVO.setRoleName(relationDO.getSubRoleName());
            memberVO.setSourceName(MemberRegisterSourceEnum.getCodeMessage(relationDO.getSubMember().getSource()));
            memberVO.setRegisterTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
            memberVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
            memberVO.setStatus(relationDO.getStatus());
            memberVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));
            memberVO.setOuterStatus(relationDO.getOuterStatus());
            memberVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
            //前端按钮显示
            memberVO.setShowCommit(relationDO.getOuterStatus().equals(MemberOuterStatusEnum.TO_PLATFORM_VERIFY.getCode()));
            memberVO.setShowUpdate(relationDO.getOuterStatus().equals(MemberOuterStatusEnum.TO_PLATFORM_VERIFY.getCode()) || relationDO.getOuterStatus().equals(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode()));
            memberVO.setShowDelete(relationDO.getOuterStatus().equals(MemberOuterStatusEnum.TO_PLATFORM_VERIFY.getCode()));
            return memberVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 获取新增会员页面内容(审核步骤、会员类型）
     *
     * @param headers HttpHeaders信息
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityAddMemberPageItemsVO> getAddMemberPageItems(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberDO memberDO = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if(memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        RoleDO roleDO = memberDO.getRoles().stream().filter(role -> role.getId().equals(loginUser.getMemberRoleId())).findFirst().orElse(null);
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        MemberAbilityAddMemberPageItemsVO itemsVO = new MemberAbilityAddMemberPageItemsVO();

        //固定审核流程
        List<WorkFlowStepVO> steps = new ArrayList<>();
        WorkFlowStepVO stepVO = new WorkFlowStepVO();
        stepVO.setStep(1);
        stepVO.setRoleName(MemberStringEnum.MEMBER.getName());
        stepVO.setStepName(MemberStringEnum.MEMBER_APPLY.getName());
        steps.add(stepVO);

        stepVO = new WorkFlowStepVO();
        stepVO.setStep(2);
        stepVO.setRoleName(MemberStringEnum.PLATFORM.getName());
        stepVO.setStepName(MemberStringEnum.MEMBER_VALIDATE.getName());
        steps.add(stepVO);
        itemsVO.setVerifySteps(steps);

        itemsVO.setCurrentStep(1);

        //获取是否开启saas多租户部署
        Boolean enableMultiTenancy = siteService.isEnableMultiTenancy(headers).getData();

        //会员类型
        List<MemberTypeIdAndNameVO> memberTypeList;

        if (enableMultiTenancy) {//有开启
            //会员类型（这里返回的是Id）
            memberTypeList = baseMemberValidateService.getSubMemberTypeList(loginUser.getMemberType(), Optional.ofNullable(roleRuleService.subMemberRoles(loginUser.getMemberId())).map(Wrapper::getData).orElse(new ArrayList<>()));
        } else {//没有开启
            if(loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) {
                memberTypeList = memberTypeRepository.findAll().stream().filter(memberTypeDO -> memberTypeDO.getTypeEnum().equals(MemberTypeEnum.MERCHANT.getCode()) || memberTypeDO.getTypeEnum().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())).map(memberTypeDO -> new MemberTypeIdAndNameVO(memberTypeDO.getId(), MemberTypeEnum.getCodeMessage(memberTypeDO.getTypeEnum()))).sorted(Comparator.comparingLong(MemberTypeIdAndNameVO::getMemberTypeId)).collect(Collectors.toList());
            } else if(loginUser.getMemberType().equals(MemberTypeEnum.CHANNEL.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) {
                memberTypeList = memberTypeRepository.findAll().stream().filter(memberTypeDO -> memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())).map(memberTypeDO -> new MemberTypeIdAndNameVO(memberTypeDO.getId(), MemberTypeEnum.getCodeMessage(memberTypeDO.getTypeEnum()))).sorted(Comparator.comparingLong(MemberTypeIdAndNameVO::getMemberTypeId)).collect(Collectors.toList());
            } else {
                memberTypeList = new ArrayList<>();
            }
        }

        itemsVO.setMemberTypes(memberTypeList);

        //国家代码
        itemsVO.setCountryCodes(countryCodeRepository.findAll().stream().map(countryCodeDO -> new DropdownItem(countryCodeDO.getTypeEnum(), countryCodeDO.getCode())).collect(Collectors.toList()));

        return Wrapper.success(itemsVO);
    }

    /**
     * 根据会员类型，查询角色列表
     *
     * @param headers HttpHeaders信息
     * @param idVO    接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<List<RoleIdAndNameVO>> getAddMemberPageRoles(HttpHeaders headers, MemberTypeIdVO idVO) {
        UserLoginCacheDTO loginCacheDTO = memberCacheService.needLoginFromBusinessPlatform(headers);

        //获取是否开启saas多租户部署
        Boolean enableMultiTenancy = siteService.isEnableMultiTenancy(headers).getData();

        if (enableMultiTenancy) {
            List<RoleRuleManageVO> roleManageVOList = roleRuleService.subMemberRoles(loginCacheDTO.getMemberId()).getData();
            if (CollectionUtils.isEmpty(roleManageVOList)) {
                return Wrapper.fail(ResponseCode.MC_MS_SUB_MEMBER_NO_SUITABLE_ROLE);
            }
            return Wrapper.success(roleManageVOList.stream().filter(roleManageVO -> roleManageVO.getMemberTypeId().longValue() == idVO.getMemberTypeId()).map(roleManageVO -> new RoleIdAndNameVO(roleManageVO.getRoleId(), roleManageVO.getRoleName())).sorted(Comparator.comparing(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList()));
        } else {
            MemberTypeDO memberTypeDO = memberTypeRepository.findById(idVO.getMemberTypeId()).orElse(null);
            if (memberTypeDO == null) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_TYPE_DOES_NOT_EXIST);
            }
            //只返回该会员类型相关的角色
            List<RoleDO> roleDOList = roleRepository.findByMemberType(memberTypeDO);
            return Wrapper.success(roleDOList.stream().filter(roleDO -> !roleDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).map(roleDO -> new RoleIdAndNameVO(roleDO.getId(), roleDO.getRoleName())).sorted(Comparator.comparingLong(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList()));
        }
    }

    /**
     * 新增会员页面，根据会员类型和角色，查询等级列表
     *
     * @param headers HttpHeaders信息
     * @param typeAndRoleIdVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<List<LevelAndTagVO>> getAddMemberPageLevels(HttpHeaders headers, MemberTypeAndRoleIdVO typeAndRoleIdVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberTypeDO memberTypeDO = memberTypeRepository.findById(typeAndRoleIdVO.getMemberTypeId()).orElse(null);
        if(memberTypeDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_TYPE_DOES_NOT_EXIST);
        }

        RoleDO roleDO = roleRepository.findById(typeAndRoleIdVO.getRoleId()).orElse(null);
        if(roleDO == null || !roleDO.getMemberType().getId().equals(memberTypeDO.getId())) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //从基础等级配置表中查
        List<LevelAndTagVO> result = baseMemberLevelConfigService.listSubMemberLevels(loginUser.getMemberId(), loginUser.getMemberRoleId(), typeAndRoleIdVO.getRoleId());

        if(CollectionUtils.isEmpty(result)) {
            return Wrapper.success(Stream.of(new LevelAndTagVO(0, "")).collect(Collectors.toList()));
        }

        return Wrapper.success(result);
    }

    /**
     * 新增会员页面，选择会员类型为渠道会员时，返回渠道信息
     * @param headers HttpHeaders信息
     * @param idVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityAddMemberPageChannelVO> getAddMemberPageChannelItems(HttpHeaders headers, MemberTypeIdVO idVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberAbilityAddMemberPageChannelVO channelVO = new MemberAbilityAddMemberPageChannelVO();

        MemberTypeDO memberTypeDO = memberTypeRepository.findById(idVO.getMemberTypeId()).orElse(null);
        if(memberTypeDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_TYPE_DOES_NOT_EXIST);
        }

        if(!memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) && !memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) {
            return Wrapper.success(channelVO);
        }

        //默认显示为“二级”渠道
        channelVO.setChannelLevelTag(MemberStringEnum.MEMBER_CHANNEL_DEFAULT_LEVEL_TAG.getName());
        channelVO.setChannelTypes(channelTypeRepository.findAll(Sort.by("id").ascending()).stream().map(channelTypeDO -> new ChannelTypeIdAndNameVO(channelTypeDO.getId(), MemberChannelTypeEnum.getMsg(channelTypeDO.getChannelTypeEnum()))).collect(Collectors.toList()));

        //上级会员列表
        List<MemberRelationDO> upperMembers = relationRepository.findBySubMemberIdAndSubRoleIdAndRelType(loginUser.getMemberId(), loginUser.getMemberRoleId(), MemberRelationTypeEnum.OTHER.getCode());
        channelVO.setUpperMembers(CollectionUtils.isEmpty(upperMembers) ? Stream.of(new UpperRelationIdAndNameVO(0L, "")).collect(Collectors.toList()) : upperMembers.stream().map(relationDO -> new UpperRelationIdAndNameVO(relationDO.getId(), relationDO.getMember().getName())).collect(Collectors.toList()));

        return Wrapper.success(channelVO);
    }

    /**
     * 根据上级会员Id，查询省列表
     *
     * @param headers  Http头部信息
     * @param idVO 接口参数
     * @return 返回信息
     */
    @Override
    public Wrapper<List<CountryAreaCodeNameVO>> getProvinceList(HttpHeaders headers, UpperRelationIdVO idVO) {
        memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.getProvinceList(idVO.getUpperRelationId());
    }

    /**
     * 根据上级会员Id和省编码，查询市列表
     *
     * @param headers Http头部信息
     * @param codeVO  接口参数
     * @return 返回信息
     */
    @Override
    public Wrapper<List<CountryAreaCodeNameVO>> getCityList(HttpHeaders headers, UpperRelationIdAndAreaCodeVO codeVO) {
        memberCacheService.needLoginFromBusinessPlatform(headers);
        return baseMemberValidateService.getCityList(codeVO.getUpperRelationId(), codeVO.getProvinceCode());
    }

    /**
     * 新增会员页面，根据选择的角色，返回会员注册资料信息
     * @param headers HttpHeaders信息
     * @param idVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<List<MemberConfigGroupVO>> getAddMemberPageMemberConfigItems(HttpHeaders headers, RoleIdVO idVO) {
        memberCacheService.needLoginFromBusinessPlatform(headers);
        RoleDO roleDO = roleRepository.findById(idVO.getRoleId()).orElse(null);
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        return Wrapper.success(baseMemberRegisterDetailService.groupMemberConfig(new ArrayList<>(roleDO.getConfigs())));
    }

    /**
     * 新增会员
     *
     * @param headers HttpHeaders信息
     * @param memberVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> addSubMember(HttpHeaders headers, MemberAbilityAddMemberVO memberVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //规则：
        // 1). 上级会员角色为企业会员，下级会员角色为企业会员：无限制
        // 2). 上级会员角色为企业会员，下级会员角色为渠道会员：不允许创建
        // 3). 上级会员角色为渠道会员，下级会员角色为企业会员：不允许创建
        // 4). 上级会员角色为渠道会员，下级会员角色为渠道会员：判断下级会员是否有另一个服务消费者角色在关系树中

        //查询平台会员关系
        MemberRelationDO platformRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(loginUser.getMemberId(), loginUser.getMemberRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());
        if(platformRelationDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //查询当前会员，即上级会员
        MemberDO upperMember = platformRelationDO.getSubMember();
        if(upperMember == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        RoleDO upperRole = platformRelationDO.getSubRole();
        if(upperRole == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //校验规则：如果上级会员未审核通过，不能创建下级会员
        if(!platformRelationDO.getVerified().equals(EnableDisableStatus.ENABLE.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_UPPER_MEMBER_VALIDATE_NOT_PASSED);
        }

        //查询平台会员和平台角色
        MemberDO platformMemberDO = memberRepository.findFirstByAccount(ServiceConfig.PLATFORM_SUPER_ADMIN_ACCOUNT);
        if (platformMemberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_REGISTER_BEFORE_PLATFORM_MEMBER_CREATE);
        }

        RoleDO platformRoleDO = platformMemberDO.getRoles().stream().filter(r -> r.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).findFirst().orElse(null);
        if (platformRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_REGISTER_BEFORE_PLATFORM_MEMBER_CREATE);
        }

        //检查手机号是否已经存在
        if(memberUserRepository.existsByRelTypeAndPhone(MemberRelationTypeEnum.OTHER.getCode(), memberVO.getPhone())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_PHONE_EXISTS);
        }

        //判断邮箱（如果非空）是否存在
        if(StringUtils.hasLength(memberVO.getEmail()) && memberUserRepository.existsByRelTypeAndEmail(MemberRelationTypeEnum.OTHER.getCode(), memberVO.getEmail().trim())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_EMAIL_EXISTS);
        }

        //校验会员类型
        MemberTypeDO memberTypeDO = memberTypeRepository.findById(memberVO.getMemberTypeId()).orElse(null);
        if (memberTypeDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_TYPE_DOES_NOT_EXIST);
        }

        Integer subMemberLevelTypeEnum = MemberLevelTypeEnum.getCodeByMemberType(memberTypeDO.getTypeEnum());

        //校验角色：通过角色Id查找角色，通过会员类型校验角色
        RoleDO newRoleDO = roleRepository.findById(memberVO.getRoleId()).orElse(null);
        if (newRoleDO == null || !newRoleDO.getMemberType().getId().equals(memberTypeDO.getId())) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //校验规则：
        if((upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT.getCode()) || upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) && (newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode()))) {
            return Wrapper.fail(ResponseCode.MC_MS_MERCHANT_MEMBER_CAN_ONLY_CREATE_MERCHANT_MEMBER);
        }

        if((upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) && (newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT.getCode()) || newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode()))) {
            return Wrapper.fail(ResponseCode.MC_MS_CHANNEL_MEMBER_CAN_ONLY_CREATE_CHANNEL_MEMBER);
        }

        //校验基础等级配置：通过角色、等级类型校验等级
        //这里要与获得等级列表接口中的对应
        if(NumberUtil.notNullOrZero(memberVO.getLevel()) && !baseMemberLevelConfigService.existLevel(loginUser.getMemberId(), loginUser.getMemberRoleId(), memberVO.getRoleId(), memberVO.getLevel())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_LEVEL_DOES_NOT_EXIST);
        }

        //校验国家代码
        CountryCodeDO countryCodeDO = countryCodeRepository.findById(memberVO.getCountryCodeId()).orElse(null);
        if(countryCodeDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_COUNTRY_CODE_DOES_NOT_EXIST);
        }

        //校验注册资料和会员名称
        List<MemberRegisterDetailDO> registerDetails = new ArrayList<>();
        Wrapper<String> checkResult = baseMemberRegisterDetailService.checkMemberRegisterDetail(memberVO.getDetail(), new ArrayList<>(newRoleDO.getConfigs()), registerDetails, memberVO.getPhone());
        if(checkResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(checkResult.getCode(), checkResult.getMessage());
        }

        String memberName = checkResult.getData();
        //会员名称是否已经注册
        if(StringUtils.hasLength(memberName) && memberRepository.existsByName(memberName)) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_NAME_REGISTERED);
        }

        //如果是渠道会员，判断条件
        MemberChannelDO memberChannelDO = null;
        if(memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) {
            Wrapper<MemberChannelDO> channelResult = baseMemberValidateService.checkChannelAgentAreas(memberVO.getUpperRelationId(), loginUser.getMemberId(), loginUser.getMemberRoleId(), memberVO.getChannelTypeId(), memberVO.getAreas(), memberVO.getRemark());
            if(channelResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(channelResult.getCode(), channelResult.getMessage());
            }

            memberChannelDO = channelResult.getData();
        }

        String md5Password;
        try {
            md5Password = PasswordUtil.instance().passwordToMd5String(ServiceConfig.PLATFORM_ADD_MEMBER_DEFAULT_PASSWORD);
        } catch (Exception e) {
            return Wrapper.fail(ResponseCode.MD5_ERROR);
        }

        //根据角色查找平台会员审核流程的Key
        Wrapper<ProcessBO> processResult = basePlatformProcessService.findRolePlatformProcess(newRoleDO);
        if(processResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(processResult.getCode(), processResult.getMessage());
        }

        //新增平台会员
        AddMemberBO addMemberBO = new AddMemberBO();
        addMemberBO.setPlatformProcess(processResult.getData());
        addMemberBO.setUpperMember(platformMemberDO);
        addMemberBO.setUpperRole(platformRoleDO);
        addMemberBO.setRoleDO(newRoleDO);
        addMemberBO.setMemberTypeDO(memberTypeDO);
        addMemberBO.setBusinessTypeDO(newRoleDO.getBusinessType());
        addMemberBO.setRegisterDetails(registerDetails);
        addMemberBO.setName(memberName);
        addMemberBO.setCountryCode(countryCodeDO.getCode());
        addMemberBO.setPhone(memberVO.getPhone());
        //设置内部状态（如果为“申请注册状态”则不自动向工作流发起启动审核步骤命令）
        addMemberBO.setInnerStatus(processResult.getData().getEmptyProcess() ? PlatformInnerStatusEnum.TO_BE_COMMIT.getCode() : PlatformInnerStatusEnum.REGISTERING.getCode());
        //会员手机号即账号
        addMemberBO.setAccount(memberVO.getPhone());
        addMemberBO.setPassword(md5Password);
        addMemberBO.setEmail(StringUtils.hasLength(memberVO.getEmail()) ?  memberVO.getEmail().trim() : "");
        //会员创建下级会员，外部审核记录的操作角色为上级会员角色
        addMemberBO.setOperatorRoleName(upperRole.getRoleName());

        //根据会员类型判断注册来源为：商户代录入注册
        if(upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT.getCode()) || upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) {
            addMemberBO.setSource(MemberRegisterSourceEnum.FROM_MERCHANT_IMPORT);
        } else {
            addMemberBO.setSource(MemberRegisterSourceEnum.FROM_CHANNEL_IMPORT);
        }

        //会员等级设置为Null，查询最小等级
        addMemberBO.setLevel(null);
        Wrapper<MemberRelationDO> result = memberInnerService.addPlatformMember(addMemberBO);
        if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(result.getCode(), result.getMessage());
        }

        //新增当前会员的下级会员（上下级关系）
        return memberInnerService.addMemberRelation(upperMember, upperRole, result.getData(), newRoleDO, memberTypeDO, memberVO.getLevel(), subMemberLevelTypeEnum, memberChannelDO);
    }

    /**
     * 引入单个/多个会员
     * @param headers Http头部信息
     * @param memberListVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> introduceSubMember(HttpHeaders headers, MemberAbilityAddMemberListVO memberListVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        memberListVO.getList().forEach(memberVO -> {
            //规则：
            // 1). 上级会员角色为企业会员，下级会员角色为企业会员：无限制
            // 2). 上级会员角色为企业会员，下级会员角色为渠道会员：不允许创建
            // 3). 上级会员角色为渠道会员，下级会员角色为企业会员：不允许创建
            // 4). 上级会员角色为渠道会员，下级会员角色为渠道会员：判断下级会员是否有另一个服务消费者角色在关系树中

            //查询平台会员关系
            MemberRelationDO platformRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(loginUser.getMemberId(), loginUser.getMemberRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());
            if(platformRelationDO == null) {
                throw new BusinessException(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
            }

            //查询当前会员，即上级会员
            MemberDO upperMember = platformRelationDO.getSubMember();
            if(upperMember == null) {
                throw new BusinessException(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
            }

            RoleDO upperRole = platformRelationDO.getSubRole();
            if(upperRole == null) {
                throw new BusinessException(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
            }

            //校验规则：如果上级会员未审核通过，不能创建下级会员
            if(!platformRelationDO.getVerified().equals(EnableDisableStatus.ENABLE.getCode())) {
                throw new BusinessException(ResponseCode.MC_MS_UPPER_MEMBER_VALIDATE_NOT_PASSED);
            }

            //查询平台会员和平台角色
            MemberDO platformMemberDO = memberRepository.findFirstByAccount(ServiceConfig.PLATFORM_SUPER_ADMIN_ACCOUNT);
            if (platformMemberDO == null) {
                throw new BusinessException(ResponseCode.MC_MS_CANNOT_REGISTER_BEFORE_PLATFORM_MEMBER_CREATE);
            }

            RoleDO platformRoleDO = platformMemberDO.getRoles().stream().filter(r -> r.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).findFirst().orElse(null);
            if (platformRoleDO == null) {
                throw new BusinessException(ResponseCode.MC_MS_CANNOT_REGISTER_BEFORE_PLATFORM_MEMBER_CREATE);
            }
            //校验会员类型
            MemberTypeDO memberTypeDO = memberTypeRepository.findById(memberVO.getMemberTypeId()).orElse(null);
            if (memberTypeDO == null) {
                throw new BusinessException(ResponseCode.MC_MS_MEMBER_TYPE_DOES_NOT_EXIST);
            }

            Integer subMemberLevelTypeEnum = MemberLevelTypeEnum.getCodeByMemberType(memberTypeDO.getTypeEnum());

            //校验角色：通过角色Id查找角色，通过会员类型校验角色
            RoleDO newRoleDO = roleRepository.findById(memberVO.getRoleId()).orElse(null);
            if (newRoleDO == null || !newRoleDO.getMemberType().getId().equals(memberTypeDO.getId())) {
                throw new BusinessException(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
            }

            //校验规则：
            if((upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT.getCode()) || upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) && (newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode()))) {
                throw new BusinessException(ResponseCode.MC_MS_MERCHANT_MEMBER_CAN_ONLY_CREATE_MERCHANT_MEMBER);
            }

            if((upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || upperRole.getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) && (newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT.getCode()) || newRoleDO.getMemberType().getTypeEnum().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode()))) {
                throw new BusinessException(ResponseCode.MC_MS_CHANNEL_MEMBER_CAN_ONLY_CREATE_CHANNEL_MEMBER);
            }

            //校验基础等级配置：通过角色、等级类型校验等级
            //这里要与获得等级列表接口中的对应
//            if(NumberUtil.notNullOrZero(memberVO.getLevel()) && !baseMemberLevelConfigService.existLevel(loginUser.getMemberId(), loginUser.getMemberRoleId(), memberVO.getRoleId(), memberVO.getLevel())) {
//                throw new BusinessException(ResponseCode.MC_MS_MEMBER_LEVEL_DOES_NOT_EXIST);
//            }

            //校验国家代码
            CountryCodeDO countryCodeDO = countryCodeRepository.findById(memberVO.getCountryCodeId()).orElse(null);
            if(countryCodeDO == null) {
                throw new BusinessException(ResponseCode.MC_MS_COUNTRY_CODE_DOES_NOT_EXIST);
            }

            //校验注册资料和会员名称
            List<MemberRegisterDetailDO> registerDetails = new ArrayList<>();
            Wrapper<String> checkResult = baseMemberRegisterDetailService.checkMemberRegisterDetail(memberVO.getDetail(), new ArrayList<>(newRoleDO.getConfigs()), registerDetails, memberVO.getPhone());
            if(checkResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                throw new BusinessException(checkResult.getCode(), checkResult.getMessage());
            }

            String memberName = checkResult.getData();

            //如果是渠道会员，判断条件
            MemberChannelDO memberChannelDO = null;
            if(memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) {
                Wrapper<MemberChannelDO> channelResult = baseMemberValidateService.checkChannelAgentAreas(memberVO.getUpperRelationId(), loginUser.getMemberId(), loginUser.getMemberRoleId(), memberVO.getChannelTypeId(), memberVO.getAreas(), memberVO.getRemark());
                if(channelResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                    throw new BusinessException(channelResult.getCode(), channelResult.getMessage());
                }

                memberChannelDO = channelResult.getData();
            }

            String md5Password;
            try {
                md5Password = PasswordUtil.instance().passwordToMd5String(ServiceConfig.PLATFORM_ADD_MEMBER_DEFAULT_PASSWORD);
            } catch (Exception e) {
                throw new BusinessException(ResponseCode.MD5_ERROR);
            }

            //根据角色查找平台会员审核流程的Key
            Wrapper<ProcessBO> processResult = basePlatformProcessService.findRolePlatformProcess(newRoleDO);
            if(processResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                throw new BusinessException(processResult.getCode(), processResult.getMessage());
            }

            //查询新导入的会员(也就是下级)与平台会员关系
            MemberRelationDO subPlatformRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(memberVO.getMemberId(), memberVO.getRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());

            //新增当前会员的下级会员（上下级关系）
            memberInnerService.addMemberRelation(upperMember, upperRole, subPlatformRelationDO, newRoleDO, memberTypeDO, memberVO.getLevel(), subMemberLevelTypeEnum, memberChannelDO);
        });
        return Wrapper.success();
    }

    /**
     * 查询单个会员详细信息（用于修改页面）
     *
     * @param headers HttpHeaders信息
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityImportMemberDetailVO> getSubMember(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getSubMemberId().equals(validateVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        MemberDO subMember = relationDO.getSubMember();
        if(subMember == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        RoleDO subRole = relationDO.getSubRole();
        if(subRole == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        CountryCodeDO countryCodeDO = null;
        if(StringUtils.hasLength(relationDO.getSubMember().getCountryCode())) {
            countryCodeDO = countryCodeRepository.findFirstByCode(relationDO.getSubMember().getCountryCode());
        }

        MemberAbilityImportMemberDetailVO detailVO = new MemberAbilityImportMemberDetailVO();
        //审核流程
        detailVO.setVerifySteps(baseMemberValidateService.getPlatformValidateOuterSteps(subRole.getRoleName()));

        //当前步骤
        detailVO.setCurrentStep(2);

        //基本信息
        detailVO.setMemberId(subMember.getId());
        detailVO.setName(subMember.getName());
        detailVO.setStatus(relationDO.getStatus());
        detailVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));
        detailVO.setOuterStatus(relationDO.getOuterStatus());
        detailVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
        detailVO.setMemberTypeEnum(relationDO.getSubMemberTypeEnum());
        detailVO.setMemberTypeId(subRole.getMemberType().getId());
        detailVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(subRole.getMemberType().getTypeEnum()));
        detailVO.setRoleId(relationDO.getSubRoleId());
        detailVO.setRoleName(relationDO.getSubRoleName());
        detailVO.setLevelId(relationDO.getLevelRight().getLevelConfig() == null ? 0L : relationDO.getLevelRight().getLevelConfig().getId());
        detailVO.setLevel(relationDO.getLevelRight().getLevel());
        detailVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
        detailVO.setAccount(relationDO.getSubMember().getAccount());
        detailVO.setCountryCodeId(countryCodeDO == null ? 0L : countryCodeDO.getId());
        detailVO.setCountryCode(countryCodeDO == null ? "" : countryCodeDO.getCode());
        detailVO.setPhone(relationDO.getSubMember().getPhone());
        detailVO.setEmail(StringUtils.hasLength(relationDO.getSubMember().getEmail()) ? relationDO.getSubMember().getEmail() : "");
        detailVO.setCreateTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
        //渠道信息
        if(relationDO.getSubMemberLevelTypeEnum().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
            detailVO.setUpperMemberId(CollectionUtils.isEmpty(relationDO.getChannel().getAgentArea().getAreas()) ? 0L : relationDO.getChannel().getAgentArea().getUpperRelationId());
            detailVO.setChannelLevelTag(relationDO.getChannel().getChannelLevelTag());
            detailVO.setChannelTypeId(relationDO.getChannel().getChannelType().getId());
            detailVO.setAreaCodes(AgentAreaUtil.transferToCodeList(relationDO.getChannel().getAgentArea()));
            detailVO.setRemark(relationDO.getChannel().getRemark());
        } else {
            detailVO.setChannelLevelTag("");
            detailVO.setChannelTypeId(0L);
            detailVO.setAreaCodes(new ArrayList<>());
            detailVO.setUpperMemberId(0L);
            detailVO.setRemark("");
        }

        //详细信息分组内容
        detailVO.setGroups(baseMemberRegisterDetailService.switchMemberRegisterDetail(subMember));

        //外部审核历史记录
        detailVO.setOuterHistory(baseMemberHistoryService.listMemberOuterHistory(relationDO));

        return Wrapper.success(detailVO);
    }

    /**
     * 查询单个会员详细信息（用于查询页面）
     *
     * @param headers    HttpHeader信息
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberAbilityImportMemberTextDetailVO> getSubMemberDetail(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getSubMemberId().equals(validateVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        MemberDO subMember = relationDO.getSubMember();
        if(subMember == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        RoleDO subRole = relationDO.getSubRole();
        if(subRole == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        CountryCodeDO countryCodeDO = null;
        if(StringUtils.hasLength(relationDO.getSubMember().getCountryCode())) {
            countryCodeDO = countryCodeRepository.findFirstByCode(relationDO.getSubMember().getCountryCode());
        }

        MemberAbilityImportMemberTextDetailVO detailVO = new MemberAbilityImportMemberTextDetailVO();
        //审核流程
        detailVO.setVerifySteps(baseMemberValidateService.getPlatformValidateOuterSteps(subRole.getRoleName()));

        //当前步骤
        detailVO.setCurrentStep(2);

        //基本信息
        detailVO.setMemberId(subMember.getId());
        detailVO.setName(subMember.getName());
        detailVO.setStatusName(MemberStatusEnum.getCodeMessage(relationDO.getStatus()));
        detailVO.setOuterStatus(relationDO.getOuterStatus());
        detailVO.setOuterStatusName(MemberOuterStatusEnum.getCodeMsg(relationDO.getOuterStatus()));
        detailVO.setMemberTypeEnum(relationDO.getSubMemberTypeEnum());
        detailVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(subRole.getMemberType().getTypeEnum()));
        detailVO.setRoleName(relationDO.getSubRoleName());
        detailVO.setLevel(relationDO.getLevelRight().getLevel());
        detailVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
        detailVO.setAccount(relationDO.getSubMember().getAccount());
        detailVO.setCountryCode(countryCodeDO == null ? "" : countryCodeDO.getCode());
        detailVO.setPhone(relationDO.getSubMember().getPhone());
        detailVO.setEmail(StringUtils.hasLength(relationDO.getSubMember().getEmail()) ? relationDO.getSubMember().getEmail() : "");
        detailVO.setCreateTime(relationDO.getCreateTime().format(ServiceConfig.DEFAULT_DATETIME_FORMATTER));
        //渠道信息
        if(relationDO.getSubMemberLevelTypeEnum().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
            detailVO.setChannelLevelTag(relationDO.getChannel().getChannelLevelTag());
            detailVO.setAreas(AgentAreaUtil.transferToList(relationDO.getChannel().getAgentArea()));
            detailVO.setRemark(relationDO.getChannel().getRemark());
        } else {
            detailVO.setChannelLevelTag("");
            detailVO.setAreas(new ArrayList<>());
            detailVO.setRemark("");
        }

        //详细信息分组内容
        detailVO.setGroups(baseMemberRegisterDetailService.switchMemberRegisterDetailText(subMember));

        //外部审核历史记录
        detailVO.setOuterHistory(baseMemberHistoryService.listMemberOuterHistory(relationDO));

        return Wrapper.success(detailVO);
    }

    /**
     * 修改会员信息
     *
     * @param headers HttpHeaders信息
     * @param updateVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateSubMember(HttpHeaders headers, MemberAbilityUpdateMemberVO updateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberRelationDO relationDO = relationRepository.findById(updateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId()) || !relationDO.getRoleId().equals(loginUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //平台与会员的关系
        MemberRelationDO platformMemberRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(relationDO.getSubMemberId(), relationDO.getSubRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());
        if(platformMemberRelationDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //审核不通过、待提交审核状态的会员都可以修改，修改后状态为待提交审核
        if(!platformMemberRelationDO.getOuterStatus().equals(MemberOuterStatusEnum.PLATFORM_VERIFYING.getCode()) && !platformMemberRelationDO.getOuterStatus().equals(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_UPDATE_OR_DELETE_SUB_MEMBER_HAS_BEEN_COMMIT);
        }

        //查询当前会员，即上级会员
        MemberDO upperMember = memberRepository.findById(loginUser.getMemberId()).orElse(null);
        if(upperMember == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        RoleDO upperRole = roleRepository.findById(loginUser.getMemberRoleId()).orElse(null);
        if(upperRole == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //要修改的会员
        MemberDO subMember = relationDO.getSubMember();
        if(subMember == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        //如果注册来源不是“商户代录入注册或渠道代录入注册，不允许修改
        if(!subMember.getSource().equals(MemberRegisterSourceEnum.FROM_MERCHANT_IMPORT.getCode()) && !subMember.getSource().equals(MemberRegisterSourceEnum.FROM_CHANNEL_IMPORT.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_SUB_MEMBER_REGISTER_FROM_OTHER_SOURCE);
        }

        //如果是其他会员的下级会员，不能修改或删除
        if(relationRepository.existsBySubMemberIdAndSubRoleIdAndRelTypeAndIdNot(relationDO.getSubMemberId(), relationDO.getSubRoleId(), MemberRelationTypeEnum.OTHER.getCode(), relationDO.getId())) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_DELETE_OTHER_SUB_MEMBER);
        }

        //要修改的会员的管理员账号（用于判断手机号是否已经注册）
        MemberUserDO userDO = subMember.getUsers().stream().filter(memberUserDO -> memberUserDO.getTypeEnum().equals(MemberUserAuthTypeEnum.ADMIN.getCode())).findFirst().orElse(null);
        if(userDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_DOES_NOT_EXIST);
        }

        //判断手机号码是否已经被注册
        if(!updateVO.getPhone().equals(userDO.getPhone()) && memberUserRepository.existsByRelTypeAndPhoneAndIdNot(MemberRelationTypeEnum.OTHER.getCode(), updateVO.getPhone(), userDO.getId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_PHONE_EXISTS);
        }

        //校验会员类型
        MemberTypeDO memberTypeDO = memberTypeRepository.findById(updateVO.getMemberTypeId()).orElse(null);
        if (memberTypeDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_TYPE_DOES_NOT_EXIST);
        }

        //校验角色：通过角色Id查找角色，通过会员类型校验角色
        RoleDO newRoleDO = roleRepository.findById(updateVO.getRoleId()).orElse(null);
        if (newRoleDO == null || !newRoleDO.getMemberType().getId().equals(memberTypeDO.getId())) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //校验等级：通过角色、等级类型校验等级
        if(!NumberUtil.isNullOrZero(updateVO.getLevel()) && !baseMemberLevelConfigService.existLevel(loginUser.getMemberId(), loginUser.getMemberRoleId(), updateVO.getRoleId(), updateVO.getLevel())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_LEVEL_DOES_NOT_EXIST);
        }

        //校验国家代码
        CountryCodeDO countryCodeDO = countryCodeRepository.findById(updateVO.getCountryCodeId()).orElse(null);
        if(countryCodeDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_COUNTRY_CODE_DOES_NOT_EXIST);
        }

        //校验注册资料和会员名称
        List<MemberRegisterDetailDO> registerDetails = new ArrayList<>();
        Wrapper<String> checkResult = baseMemberRegisterDetailService.checkMemberRegisterDetail(updateVO.getDetail(), new ArrayList<>(newRoleDO.getConfigs()), registerDetails, subMember.getName());
        if(checkResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(checkResult.getCode(), checkResult.getMessage());
        }

        String memberName = checkResult.getData();
        //会员名称是否已经注册
        if(StringUtils.hasLength(memberName) && memberRepository.existsByNameAndIdNot(memberName, updateVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_NAME_REGISTERED);
        }

        //如果是渠道会员，判断条件
        ChannelTypeDO channelTypeDO = null;
        List<AgentAreaBO> areaBOList = new ArrayList<>();
        if(memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || memberTypeDO.getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())) {
            channelTypeDO = channelTypeRepository.findById(updateVO.getChannelTypeId()).orElse(null);
            if(channelTypeDO == null) {
                return Wrapper.fail(ResponseCode.MC_MS_MEMBER_CHANNEL_TYPE_DOES_NOT_EXIST);
            }

            Wrapper<Void> updateResult = baseMemberValidateService.updateChannelAgentAreas(relationDO, updateVO.getUpperRelationId(), loginUser.getMemberId(), loginUser.getMemberRoleId(), updateVO.getChannelTypeId(), updateVO.getAreas(), updateVO.getRemark());
            if(updateResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(updateResult.getCode(), updateResult.getMessage());
            }
        }

        //修改平台会员关系
        UpdatePlatformMemberBO updateBO = new UpdatePlatformMemberBO();
        updateBO.setRelationDO(platformMemberRelationDO);
        updateBO.setRoleDO(newRoleDO);
        updateBO.setMemberTypeDO(memberTypeDO);
        updateBO.setRegisterDetails(registerDetails);
        //不能修改平台会员的等级
        updateBO.setLevel(platformMemberRelationDO.getLevelRight().getLevel());
        updateBO.setName(memberName);
        updateBO.setPhone(updateVO.getPhone());
        updateBO.setCountryCode(countryCodeDO.getCode());
        updateBO.setEmail(StringUtils.hasLength(updateVO.getEmail()) ? updateVO.getEmail() : "");
        Wrapper<Void> updatePlatformMemberResult = memberInnerService.updatePlatformMember(updateBO);
        if(updatePlatformMemberResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return updatePlatformMemberResult;
        }

        //修改上下级关系
        UpdateMemberRelationBO updateRelationBO = new UpdateMemberRelationBO();
        updateRelationBO.setUpperMember(upperMember);
        updateRelationBO.setUpperRole(upperRole);
        updateRelationBO.setSubMember(subMember);
        updateRelationBO.setSubRoleDO(newRoleDO);
        updateRelationBO.setRelationDO(relationDO);
        updateRelationBO.setMemberTypeDO(memberTypeDO);
        updateRelationBO.setName(memberName);
        updateRelationBO.setChannelTypeDO(channelTypeDO);
        updateRelationBO.setLevel(updateVO.getLevel());
        updateRelationBO.setChannelLevelTag(MemberStringEnum.MEMBER_CHANNEL_DEFAULT_LEVEL_TAG.getName());
        updateRelationBO.setAreas(areaBOList);
        updateRelationBO.setRemark(StringUtils.hasLength(updateVO.getRemark()) ? updateVO.getRemark() : "");

        return memberInnerService.updateMemberRelation(updateRelationBO);
    }

    /**
     * 删除会员
     *
     * @param headers HttpHeaders信息
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> deleteSubMember(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberDO memberDO = memberRepository.findById(validateVO.getMemberId()).orElse(null);
        if(memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getMemberId().equals(loginUser.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //如果已经提交审核，不允许修改
        if(!relationDO.getOuterStatus().equals(MemberOuterStatusEnum.TO_PLATFORM_VERIFY.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_UPDATE_OR_DELETE_SUB_MEMBER_HAS_BEEN_COMMIT);
        }

        //如果注册来源不是“商户代录入注册，不允许修改
        if(!memberDO.getSource().equals(MemberRegisterSourceEnum.FROM_MERCHANT_IMPORT.getCode()) && !memberDO.getSource().equals(MemberRegisterSourceEnum.FROM_CHANNEL_IMPORT.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_SUB_MEMBER_REGISTER_FROM_OTHER_SOURCE);
        }

        //查询平台会员和平台角色
        MemberDO platformMemberDO = memberRepository.findFirstByAccount(ServiceConfig.PLATFORM_SUPER_ADMIN_ACCOUNT);
        if (platformMemberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_REGISTER_BEFORE_PLATFORM_MEMBER_CREATE);
        }

        RoleDO platformRoleDO = platformMemberDO.getRoles().stream().filter(r -> r.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).findFirst().orElse(null);
        if (platformRoleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_CANNOT_REGISTER_BEFORE_PLATFORM_MEMBER_CREATE);
        }

        MemberRelationDO platformRelationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(platformMemberDO.getId(), platformRoleDO.getId(), relationDO.getSubMemberId(), relationDO.getSubRoleId());
        if(platformRelationDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //如果是其他会员的下级会员，仅删除上下级关系，否则全部删除
        Specification<MemberRelationDO> specification = (Specification<MemberRelationDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.notEqual(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.notEqual(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), relationDO.getSubMemberId()));
            list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), relationDO.getSubRoleId()));
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        if(relationRepository.count(specification) > 0) {
            return memberInnerService.deleteMemberRelation(relationDO);
        } else {
            Wrapper<Void> result = memberInnerService.deletePlatformMember(memberDO, platformRelationDO);
            if(result.getCode() != ResponseCode.SUCCESS.getCode()) {
                return result;
            }

            return memberInnerService.deleteMemberRelation(relationDO);
        }
    }

    /**
     * 提交平台审核
     *
     * @param headers Http头部信息
     * @param validateVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> commitSubMemberToValidate(HttpHeaders headers, MemberValidateVO validateVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //当前会员的上下级关系
        MemberRelationDO relationDO = relationRepository.findById(validateVO.getValidateId()).orElse(null);
        if(relationDO == null || !relationDO.getSubMemberId().equals(validateVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //提交平台审核后，要将外部状态置为“待平台审核”，以此判断是否已经提交过了
        if(!relationDO.getOuterStatus().equals(MemberOuterStatusEnum.TO_PLATFORM_VERIFY.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_SUB_MEMBER_HAS_BEEN_COMMIT_TO_VALIDATE);
        }

        //与平台会员的上下级关系
        MemberRelationDO platformRelationDO = relationRepository.findFirstBySubMemberIdAndSubRoleIdAndRelType(relationDO.getSubMemberId(), relationDO.getSubRoleId(), MemberRelationTypeEnum.PLATFORM.getCode());
        if(platformRelationDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_RELATION_DOES_NOT_EXIST);
        }

        //启动平台审核的工作流
        //如果平台审核流程是“无需审核”，直接设置审核通过状态，不需要调用工作流
        if(platformRelationDO.getValidateTask().getProcessTypeEnum().equals(MemberProcessTypeEnum.PLATFORM_VALIDATION.getCode()) && platformRelationDO.getValidateTask().getProcessKey().equals(ServiceConfig.EMPTY_PLATFORM_VALIDATE_PROCESS_KEY)) {
            relationDO.setInnerStatus(MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL.getCode());
            relationDO.setOuterStatus(MemberOuterStatusEnum.DEPOSITING.getCode());

            //更新会员上下级关系
            relationRepository.saveAndFlush(relationDO);
        } else {
            Wrapper<WorkflowTaskResultBO> taskResult = baseWorkflowService.startMemberProcess(platformRelationDO);
            if (taskResult.getCode() != ResponseCode.SUCCESS.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }

            String taskId = taskResult.getData().getTaskId();
            Integer innerStatus = taskResult.getData().getInnerStatus();

            platformRelationDO.getValidateTask().setTaskId(taskId);
            platformRelationDO.setInnerStatus(innerStatus);
            if(innerStatus.equals(PlatformInnerStatusEnum.VERIFY_NOT_PASSED.getCode())) {
                platformRelationDO.setInnerStatus(PlatformInnerStatusEnum.VERIFY_NOT_PASSED.getCode());
                platformRelationDO.setOuterStatus(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode());

                relationDO.setOuterStatus(MemberOuterStatusEnum.PLATFORM_VERIFY_NOT_PASSED.getCode());
            } else if(innerStatus.equals(PlatformInnerStatusEnum.VERIFY_PASSED.getCode())) {
                platformRelationDO.setInnerStatus(PlatformInnerStatusEnum.VERIFY_PASSED.getCode());
                platformRelationDO.setOuterStatus(MemberOuterStatusEnum.PLATFORM_VERIFY_PASSED.getCode());
                platformRelationDO.setVerified(MemberValidateStatusEnum.VERIFY_PASSED.getCode());
                platformRelationDO.setDepositTime(LocalDateTime.now());

                relationDO.setInnerStatus(MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL.getCode());
                relationDO.setOuterStatus(MemberOuterStatusEnum.DEPOSITING.getCode());
            } else {
                innerStatus = PlatformInnerStatusEnum.TO_BE_COMMIT.getCode();
                platformRelationDO.setInnerStatus(innerStatus);
                platformRelationDO.setOuterStatus(MemberOuterStatusEnum.TO_PLATFORM_VERIFY.getCode());

                relationDO.setInnerStatus(MemberInnerStatusEnum.TO_VERIFY_DEPOSITORY_DETAIL.getCode());
                relationDO.setOuterStatus(MemberOuterStatusEnum.PLATFORM_VERIFYING.getCode());
            }

            //更新平台上下级关系、会员上下级关系
            relationRepository.saveAll(Stream.of(platformRelationDO, relationDO).collect(Collectors.toList()));

            //通知报表服务进行统计“平台后台首页 - 新增会员数”
            reportFeignService.reportPlatformMemberValidate(platformRelationDO.getId(), platformRelationDO.getMemberId(), platformRelationDO.getRoleId(),null, innerStatus);
        }

        //记录内部记录
        baseMemberHistoryService.saveMemberInnerHistory(relationDO, loginUser, MemberValidateHistoryOperationEnum.COMMIT_TO_VALIDATE,"");

        return Wrapper.success();
    }


}
